﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class KhachHangDaiChung_KhachHangDaiChung_XemDanhSachSanPham : System.Web.UI.Page
{
    //public string GetCurrentPageName()
    //{
    //    string sPath = System.Web.HttpContext.Current.Request.Url.AbsolutePath;
    //    System.IO.FileInfo oInfo = new System.IO.FileInfo(sPath);
    //    string sRet = oInfo.Name;
    //    return sRet; 
    //}
    int RowPerPage;
    int startIndex;
    int page;
    GlobalFunctions gf;
    int khuyenmai = 0;    
    protected void Page_Load(object sender, EventArgs e)
    {
        SiteMapLoaiSanPham1.Url = "/SMO/ChucNang/NguoiDung/NguoiDung_XemDanhMucSanPham.aspx";
        DataDSTableAdapters.KHUYENMAITableAdapter kmadapter = new DataDSTableAdapters.KHUYENMAITableAdapter();
        DataDS.KHUYENMAIDataTable kmtable= kmadapter.KHUYENMAI_KiemTraCoKhuyenMaiHienHanh();
        if (kmtable.Rows.Count > 0)
            khuyenmai = 1;
        if (Request["page"] != null)
            page = int.Parse(Request["page"]);
        else
            page = 0;
       
        RowPerPage = int.Parse(ConfigurationSettings.AppSettings["RowPerPage"]);
        startIndex = (page * RowPerPage);
        

        DataDSTableAdapters.SANPHAMTableAdapter spAdapter = new DataDSTableAdapters.SANPHAMTableAdapter();
        PageInterface1.currentPageName = GlobalFunctions.GetCurrentPageName();
        PageInterface1.currentPageNumber = page;
        PageInterface1.totalNumberOfPage = (int)spAdapter.SANPHAM_TongSoDong() / RowPerPage;
        if ((int)spAdapter.SANPHAM_TongSoDong() % RowPerPage != 0)
            PageInterface1.totalNumberOfPage++;


        gf = new GlobalFunctions();
        //if (gf.IsKHTT() == 1)
        //{
        //    DataDSTableAdapters.SANPHAM_YEUTHICHTableAdapter spytadapter = new DataDSTableAdapters.SANPHAM_YEUTHICHTableAdapter();
        //    int id = (int)Session["LoginID"];
        //    DataDS.SANPHAM_YEUTHICHDataTable spTable = spytadapter.SANPHAM_LaySPYeuThichTheoCMND((string)Session["CMND"], startIndex, RowPerPage);
        //    DataList_DanhSachSanPham.DataSource = spTable;
        //    DataList_DanhSachSanPham.DataBind();
        //    PageInterface1.totalNumberOfPage = spTable.Rows.Count / RowPerPage;
        //}
        //else
        if(Request["MaPL"] != null)
        {
            int mapl = int.Parse(Request["MaPL"]);
            if (!IsPostBack)
            {
                DataList_DanhSachSanPham.DataSource = spAdapter.SANPHAM_LayTheoPhanLoai_Paged(mapl, startIndex, RowPerPage);
                DataList_DanhSachSanPham.DataBind();
            }

            ArrayList name = new ArrayList();
            name.Add("MaPL");
            ArrayList value = new ArrayList();
            value.Add(mapl);

            PageInterface1._paraName = name;
            PageInterface1._paraValue = value;
            PageInterface1.totalNumberOfPage = (int)spAdapter.sp_SANPHAM_TongSoDongTheoPhanLoai(mapl) / RowPerPage;
            
        }
        else
        {
            if (!IsPostBack)
            {
                DataList_DanhSachSanPham.DataSource = spAdapter.SANPHAM_LayTatCa_Paged(startIndex, RowPerPage);
                DataList_DanhSachSanPham.DataBind();
            }
        }
        //DataList_DanhSachSanPham.DataSource = spAdapter.SANPHAM_LayTatCa();

       // DataList_DanhSachSanPham.DataSource = spAdapter.SANPHAM_LayTatCa_Paged(startIndex,RowPerPage);
        
       
       /* DataListItem item = DataList_DanhSachSanPham.Items[0];
        HiddenField hidden = (HiddenField)item.FindControl("Id_TaiKhoan");
        if(hidden.Value=="")
            Response.Write("Khác");*/
    }
    protected void DataList_DanhSachSanPham_ItemDataBound(object sender, DataListItemEventArgs e)
    {

    }
    protected void DataList_DanhSachSanPham_ItemCreated(object sender, DataListItemEventArgs e)
    {
       /* DataListItem item = e.Item;
        //  Response.Write("dasdasd" + id_taikhoan);
        string idsp = ((DataRowView)item.DataItem).Row["Id"].ToString();
        HyperLink hyper = (HyperLink)item.FindControl("hyperlink_DauVaoDanhSach");
        hyper.Text = "Loại khỏi danh sách ưa thích";
        hyper.NavigateUrl = "../KhachHangThanThiet/KHTT_LoaiKhoiDanhSach.aspx?Id=" + idsp + "&page=" + page.ToString();
       */
            if (!this.IsPostBack)
            {
                DataListItem item = e.Item;
                string idsp = ((DataRowView)item.DataItem).Row["Id"].ToString();
                string giacu = ((DataRowView)item.DataItem).Row["GiaCu"].ToString();
                if (khuyenmai == 1)
                {
                    DataDSTableAdapters.KHUYENMAI_CHITIETTableAdapter kmctadapter = new DataDSTableAdapters.KHUYENMAI_CHITIETTableAdapter();
                    DataDS.KHUYENMAI_CHITIETDataTable kmcttable= kmctadapter.KHUYENMAI_LayChiTietTheoSP(int.Parse(idsp));
                    string skhuyenmai = "<marquee><table width='150'>Khuyến mãi";
                    //int changegia = 0;
                    int giatri=0;
                    if (kmcttable.Rows.Count > 0)
                    {
                        DateTime beg = (DateTime)kmcttable.Rows[0]["NgayBatDau"];
                        DateTime end = (DateTime)kmcttable.Rows[0]["NgayKetThuc"];
                        string sbeg = beg.ToString("dd/M/yyyy");
                        string send = end.ToString("dd/M/yyyy");
                        skhuyenmai += "<tr>";
                        skhuyenmai += "<td>Bắt đầu:" + sbeg + " <br/>Kết thúc:" + send + "</td></tr>";
                        skhuyenmai += "<tr><td>" + kmcttable[0].NoiDung + "</td></tr>";
                    }
                    Label lblgia = (Label)item.FindControl("lblGia");
                    Label lbltangkem = (Label)item.FindControl("lblTangKem");
                    lblgia.Text = giacu + " VND";
                    DataDSTableAdapters.SANPHAMTableAdapter spadapter = new DataDSTableAdapters.SANPHAMTableAdapter();
                    //for (int i = 0; i < kmcttable.Rows.Count; i++)
                    //{                        
                    //    string tenhinhthuc = kmcttable.Rows[i]["TenHinhThuc"].ToString();
                    //    int idhinhthuc = int.Parse(kmcttable.Rows[i]["Id_HinhThuc"].ToString());
                    //    giatri = int.Parse(kmcttable.Rows[i]["GiaTri"].ToString());                        
                        
                    //    if (idhinhthuc == 2)
                    //        skhuyenmai += "<br/>" + tenhinhthuc + ":<b>" + giatri.ToString() + "</b>%";
                    //    else
                    //    {
                    //        DataDSTableAdapters.SANPHAMTableAdapter spadapter = new DataDSTableAdapters.SANPHAMTableAdapter();
                    //        DataDS.SANPHAMDataTable sptable= spadapter.SANPHAM_LayTheoIdSP(giatri);
                    //        skhuyenmai += "<br/>" + tenhinhthuc + "<a href='NguoiDung_XemChiTietSanPham.aspx?MaSP="+sptable.Rows[0]["MaSP"].ToString()+"' ><img width='50' height='50' src=\""+sptable.Rows[0]["HinhAnh"].ToString().Replace("~","/SMO") + "\" /></a>";
                    //        skhuyenmai+=sptable.Rows[0]["TenSP"] +"Giá:<b>" + sptable.Rows[0]["GiaCu"].ToString()+" VND</b>";
                    //    }
                    //    skhuyenmai+="</td>";
                    //    skhuyenmai += "</tr>";
                    //    if (idhinhthuc== 2)
                    //        changegia = 1;
                    //}
                    for (int i = 0; i < kmcttable.Rows.Count; i++)
                    {

                        string tenhinhthuc = kmcttable.Rows[i]["TenHinhThuc"].ToString();
                        int idhinhthuc = int.Parse(kmcttable.Rows[i]["Id_HinhThuc"].ToString());
                        giatri = int.Parse(kmcttable.Rows[i]["GiaTri"].ToString());

                        skhuyenmai += "<tr><td>";
                        if (idhinhthuc == 2 && giatri > 0)
                        {
                            skhuyenmai += "<br/>" + tenhinhthuc + ":<b>" + giatri.ToString() + "</b>%";
                            float giamoi = float.Parse(giacu) * (100 - giatri) / 100;
                            lblgia.Text = "<strike>" + giacu + "VND </strike>" + " <b>" + giamoi.ToString() + " VND </b>";
                        }
                        else if (idhinhthuc == 1)
                        {
                            DataDS.SANPHAMDataTable spkmtable = spadapter.SANPHAM_LayTheoIdSP(giatri);
                            skhuyenmai += "<br/>" + tenhinhthuc + ":<a href='NguoiDung_XemChiTietSanPham.aspx?MaSP=" + spkmtable.Rows[0]["MaSP"].ToString() + "' ><img width='50' height='50' src=\"" + spkmtable.Rows[0]["HinhAnh"].ToString().Replace("~", "/SMO") + "\" /></a>";
                            skhuyenmai += spkmtable.Rows[0]["TenSP"] + ".Giá:<b>" + spkmtable.Rows[0]["GiaCu"].ToString() + " VND</b>";
                        }
                        skhuyenmai += "</td>";
                        skhuyenmai += "</tr>";

                    }
                    skhuyenmai += "</table></marquee>";
                    //skhuyenmai += "</table>";
                    if (kmcttable.Rows.Count > 0)
                        lbltangkem.Text = skhuyenmai;

                    //Label lblgia = (Label)item.FindControl("lblGia");
                    ////neu co giam gia thi xuat chuoi nay ra
                    //if (changegia == 1)
                    //{
                    //    float giamoi = float.Parse(giacu) * (100-giatri) / 100;
                    //    lblgia.Text = "<strike>" + giacu + "VND  </strike> " + " &nbsp&nbsp<b>" + giamoi.ToString() + " VND </b>";
                    //}
                    //else
                    //{
                    //    lblgia.Text = giacu + " VND";
                    //}
                    //Label lbltangkem = (Label)item.FindControl("lblTangKem");
                    //if(kmcttable.Rows.Count>0)
                    //    lbltangkem.Text = skhuyenmai;
                    
                }
                //if (gf.IsKHTT() == 1)
                //{
                //    string id_taikhoan = ((DataRowView)item.DataItem).Row["Id_TaiKhoan"].ToString();
                   
                //    GlobalFunctions gf = new GlobalFunctions();
                //    HyperLink hyper = (HyperLink)item.FindControl("hyperlink_DauVaoDanhSach");
                //    if (id_taikhoan != "")
                //    {
                //        hyper.Text = "Loại khỏi danh sách ưa thích";
                //        hyper.NavigateUrl = "../KhachHangThanThiet/KHTT_LoaiKhoiDanhSach.aspx?Id=" + idsp + "&page=" + page.ToString();
                //    }
                //    else
                //    {
                //        hyper.Text = "Đưa vào danh sách ưa thích";
                //        hyper.NavigateUrl = "../KhachHangThanThiet/KHTT_ThemSanPhamYeuThich.aspx?Id=" + idsp + "&page=" + page.ToString();
                //    }
                //}

            }
        
    }

    protected void DataList_DanhSachSanPham_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName == "DuaVaoGioHang")
        {
            int soluong = int.Parse(((Label)(e.Item.FindControl("lbSoLuong"))).Text);
            int giacu = int.Parse(((Label)(e.Item.FindControl("lbGiaCu"))).Text);
            int IdSP = int.Parse(e.CommandArgument.ToString());
            int soluongmua = 1;
            //lblValidate.Text = "";
            string validate = "";
            
            DataDSTableAdapters.KHUYENMAI_CHITIETTableAdapter kmctadapter = new DataDSTableAdapters.KHUYENMAI_CHITIETTableAdapter();
            DataDS.KHUYENMAI_CHITIETDataTable kmcttable = kmctadapter.KHUYENMAI_LayChiTietTheoSP(IdSP);
            int idhinhthuc = 0;
            int giatri = 0;
            if (kmcttable.Rows.Count > 0)
            {
                idhinhthuc = int.Parse(kmcttable.Rows[0]["Id_HinhThuc"].ToString());
                giatri = int.Parse(kmcttable.Rows[0]["GiaTri"].ToString());
            }
            DataTable table = (DataTable)Session["GioHang"];
            DataRow row;
            int kt = kiemTraTonTaiSanPhamTrongGioHang(IdSP.ToString());
            if (kt == -1)
            {
                if (soluongmua > soluong)
                {
                    validate = "Số lượng vượt mức cho phép!";
                    return;
                }
                row = table.NewRow();
                row["Id_HinhThuc"] = idhinhthuc;
                row["GiaTri"] = giatri;
                row["Id_SP"] = IdSP;
                row["SoLuong"] = soluongmua.ToString();
                row["DonGia"] = giacu;
                if (int.Parse(row["Id_HinhThuc"].ToString()) == 2)
                {
                    giatri = int.Parse(row["GiaTri"].ToString());
                    row["TongTien"] = soluongmua * (float.Parse(row["DonGia"].ToString()) * (100 - giatri) / 100);
                }
                else
                    row["TongTien"] = soluongmua * float.Parse(row["DonGia"].ToString());
                row["Is_KhuyenMai"] = "False";
                table.Rows.Add(row);
            }
            else
            {
                row = table.Rows[kt];
                if (int.Parse(row["SoLuong"].ToString()) + soluongmua > soluong)
                {
                    validate = "Số lượng vượt mức cho phép!";
                    return;
                }
                row["SoLuong"] = Convert.ToString(int.Parse(row["SoLuong"].ToString()) + soluongmua);
                if (int.Parse(row["Id_HinhThuc"].ToString()) == 2)
                {
                    giatri = int.Parse(row["GiaTri"].ToString());
                    row["TongTien"] = int.Parse(row["SoLuong"].ToString()) * (float.Parse(row["DonGia"].ToString()) * (100 - giatri) / 100);
                }
                else
                    row["TongTien"] = int.Parse(row["SoLuong"].ToString()) * float.Parse(row["DonGia"].ToString());
                // table.Rows.Add(row);
                // table.Rows.RemoveAt(kt);
            }
            //lay san pham khuyen mai
            if (idhinhthuc == 1)
            {
                DataDSTableAdapters.SANPHAMTableAdapter spadapter = new DataDSTableAdapters.SANPHAMTableAdapter();
                DataDS.SANPHAMDataTable sptable = spadapter.SANPHAM_LayTheoIdSP(giatri);
                kt = kiemTraTonTaiSanPhamTrongGioHang(giatri.ToString());
                if (kt == -1)
                {
                    row = table.NewRow();
                    row["Id_HinhThuc"] = -1;
                    row["GiaTri"] = 0;
                    row["Id_SP"] = giatri;
                    row["SoLuong"] = soluongmua.ToString();
                    row["DonGia"] = sptable.Rows[0]["GiaCu"].ToString();
                    row["TongTien"] = soluongmua * float.Parse(row["DonGia"].ToString());
                    row["Is_KhuyenMai"] = "True";
                    table.Rows.Add(row);
                }
                else
                {
                    row = table.Rows[kt];
                    row["SoLuong"] = Convert.ToString(int.Parse(row["SoLuong"].ToString()) + soluongmua);
                    row["TongTien"] = int.Parse(row["SoLuong"].ToString()) * float.Parse(row["DonGia"].ToString());
                    // table.Rows.Add(row);
                    // table.Rows.RemoveAt(kt);
                }
            }
            Session["GioHang"] = table;

            //hien thong bao
            DataDSTableAdapters.SANPHAMTableAdapter sptbadapter = new DataDSTableAdapters.SANPHAMTableAdapter();
            DataDS.SANPHAMDataTable sptbtable;
            string thongbao = "<center><table border='1' style='border-style:solid;'><b>Thông tin giỏ hàng của bạn<b>";
            thongbao += "<tr>" +
                        "<th>Tên SP</th>" +
                        "<th>Số Lượng</th>" +
                        "<th>Đơn Giá</th>" +
                        "<th>Thành Tiền</th>" +
                        "<th>Khuyến mãi</th>" +
                        "</tr>";
            table = (DataTable)Session["GioHang"];
            float tong = 0;
            foreach (DataRow datarow in table.Rows)
            {
                string id = datarow["Id_SP"].ToString();
                sptbtable = sptbadapter.SANPHAM_LayTheoIdSP(int.Parse(id));
                DataDS.SANPHAMRow sprow = sptbtable[0];
                thongbao += "<tr>";
                thongbao += "<td>" + sprow["TenSP"] + "</td>";
                thongbao += "<td>" + datarow["SoLuong"] + "</td>";
                thongbao += "<td>" + datarow["DonGia"] + "</td>";
                thongbao += "<td>" + datarow["TongTien"] + "</td>";
                if (datarow["Is_KhuyenMai"].ToString() == "True")
                    thongbao += "<td><b> SP Khuyến mãi</b> </td>";
                else
                {
                    if (int.Parse(datarow["Id_HinhThuc"].ToString()) == 2)
                    {
                        giatri = int.Parse(datarow["GiaTri"].ToString());
                        thongbao += "<td><b>Giảm giá:" + giatri.ToString() + " %</b></td>";
                    }
                    else
                    {
                        if (int.Parse(datarow["Id_HinhThuc"].ToString()) == 1)
                        {
                            thongbao += "<td><b>Tặng kèm sản phẩm</b></td>";
                        }
                        else
                            thongbao += "<td></td>";
                    }
                }
                thongbao += "</tr>";
                if (datarow["Is_KhuyenMai"].ToString() == "False")
                    tong += float.Parse(datarow["TongTien"].ToString());
            }
            thongbao += "<tr><td colspan='5' align='right'>Tổng tiền:" + tong.ToString() + "</td></tr>";
            thongbao += "</table></center>";
            lblGioHang.Text = thongbao;
            msg.Show();
        }
    }
    int kiemTraTonTaiSanPhamTrongGioHang(string IdSP)
    {
        DataTable table = (DataTable)Session["GioHang"];
        for (int i = 0; i < table.Rows.Count; i++)
        {
            DataRow row = table.Rows[i];
            if (row["Id_SP"].ToString() == IdSP.Trim())
                return i;
        }
        return -1;
    }
}
